import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:enterprise_v6_app/app/data/api/file_upload_apis.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_editor/image_editor.dart';
import 'package:path_provider/path_provider.dart';
import 'package:syncfusion_flutter_signaturepad/signaturepad.dart';

class SignatureController extends GetxController {
  GlobalKey<SfSignaturePadState> signaturePadKey = GlobalKey();

  // 是否显示提示文字
  RxBool isShowHint = true.obs;

  // 清除
  void clear() {
    signaturePadKey.currentState?.clear();
  }

  // 保存
  void save() async {
    final data = await signaturePadKey.currentState?.toImage();
    if (data != null) {
      // 上传签名
      SmartDialog.showLoading();
      final directory = await getTemporaryDirectory();
      final String path = '${directory.path}/signature.png';
      final byteData = await data.toByteData(format: ImageByteFormat.png);
      final Uint8List pngBytes = byteData!.buffer.asUint8List();

      // 旋转图像
      final editorOption = ImageEditorOption();
      editorOption.addOption(const RotateOption(-90));
      editorOption.outputFormat = const OutputFormat.png();
      final Uint8List? result = await ImageEditor.editImage(
        image: pngBytes,
        imageEditorOption: editorOption,
      );

      final File toFile = File(path);
      // data/user/0/com.hy.frame.flutter_frame/files/signature.png
      await toFile.writeAsBytes(result as List<int>);

      final String fileUrl = await FileUploadApis.uploadFile(
        fileUrl: path,
        fileName: 'signature.png',
      );
      SmartDialog.dismiss();
      // OpenFilex.open(path);
      back(path: fileUrl);
    } else {
      Get.snackbar('提示', '请先签名');
    }
  }

  // 返回
  void back({String? path}) {
    // changeOrientation2();
    Get.back(result: path);
  }

  @override
  void onClose() {
    signaturePadKey.currentState?.clear();
    // ignore: invalid_use_of_protected_member
    signaturePadKey.currentState?.dispose();
    super.onClose();
  }
}
